#!/bin/bash

INSTALL_BASE_DIR="$PWD/.."
INSTALL_DIR="$PWD"

echo "Installing OpenCV into: $INSTALL_DIR"

# Install opencv dependencies
echo "Installing OpenCV dependencies"
apt-get update -qq --fix-missing && \
apt-get upgrade -y && \
apt-get install -y \
    libgtk-3-dev \
    libavcodec-dev \
    libavformat-dev \
    libswscale-dev \
    libv4l-dev \
    libxvidcore-dev \
    libx264-dev \
    libx265-dev \
    libjpeg-dev \
    libpng-dev \
    libtiff-dev \
    libatlas-base-dev \
    gfortran \
    openexr \
    libtbb2 \
    libtbb-dev \
    libdc1394-22-dev \
    libgtk2.0-dev && \
    rm -rf /var/lib/apt/lists/*

apt install -y python3-pip
apt install -y python3-numpy

pip3 install pkgconfig
pip3 install numpy

ldconfig

# Download OpenCV and build from source
OPENCV_VERSION="4.10.0"
echo "Downloading OpenCV source"
cd "$INSTALL_BASE_DIR"/build


if [ ! -e "$INSTALL_BASE_DIR"/build/opencv ]; then
    wget -O "$INSTALL_BASE_DIR"/build/opencv.zip https://github.com/opencv/opencv/archive/"$OPENCV_VERSION".zip
    unzip "$INSTALL_BASE_DIR"/build/opencv.zip
    mv "$INSTALL_BASE_DIR"/build/opencv-"$OPENCV_VERSION"/ "$INSTALL_BASE_DIR"/build/opencv
    rm -rf "$INSTALL_BASE_DIR"/build/opencv.zip
fi

#wget -O "$INSTALL_BASE_DIR"/build/opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/"$OPENCV_VERSION".zip
#unzip "$INSTALL_BASE_DIR"/build/opencv_contrib.zip
#mv "$INSTALL_BASE_DIR"/build/opencv_contrib-"$OPENCV_VERSION"/ "$INSTALL_BASE_DIR"/build/opencv_contrib
#rm -rf "$INSTALL_BASE_DIR"/build/opencv_contrib.zip

echo "Configuring OpenCV"
cd "$INSTALL_BASE_DIR"/build/opencv
mkdir build
cd build

cmake -D CMAKE_BUILD_TYPE=RELEASE \
      -D OPENCV_GENERATE_PKGCONFIG=YES \
      -D CMAKE_INSTALL_PREFIX=/usr/local \
      -D OPENCV_ENABLE_NONFREE=OFF \
      -D PYTHON_EXECUTABLE=/usr/bin/python3 \
      -D BUILD_opencv_python3=ON \
      -D PYTHON_VERSION=310 \
      -D PYTHON_DEFAULT_EXECUTABLE=/usr/bin/python3.10 \
      -D PYTHON3_EXECUTABLE=/usr/bin/python3.10 \
      -D PYTHON3_PACKAGES_PATH=/usr/lib/python3/dist-packages \
      -D PYTHON3_INCLUDE_DIR=/usr/include/python3.10 \
      -D OPENCV_PYTHON3_INSTALL_PATH=/usr/local/lib/python3.10/dist-packages \
      -D PYTHON3_NUMPY_INCLUDE_DIRS=/usr/local/lib/python3.10/dist-packages/numpy/core/include \
      -D BUILD_TESTS=OFF \
      -D BUILD_PERF_TESTS=OFF \
      ..

echo "Compiling OpenCV"
make -j $(nproc)
make install
ldconfig
